
import Router from 'koa-router'
import fs from 'fs'
import config from '../../../config/config'
import {Models} from '../../../common/typings/model'
import Result from '../../../common/utils/Result'
import Fiction from '../../../service/Fiction'
import httpErrors from '../../../core/HttpException'
import Mysql from "../../../core/Mysql";
const router = new Router({
    prefix:'/api/v1/fiction'
})

interface List {
    text: string,
    author: string,
    href: string,
    type: number
    authorId?: number
}

interface Author {
    id: number
    name: string
}

const cof = [
    {
        type: 1,
        total: 2199
    },
    {
        type: 2,
        total: 623
    },
    {
        type: 3,
        total: 1559
    },
    {
        type: 4,
        total: 468
    },
    {
        type: 5,
        total: 4
    },
    {
        type: 6,
        total: 504
    },
    {
        type: 7,
        total: 613
    },
    {
        type: 8,
        total: 1574
    }
]



router.get('/getShuqugeXHList.do',async (ctx: Models.Ctx,next)=> {
   
    // await uploadJson()
    getAllChapter()
    throw new httpErrors.Success({}, '保存成功')
    return 
    try {
        // const results = await todo()
        // console.log(results!.text())
        // const results = await Fiction.getList('http://m.biquge3.com/xs/1111262')
        const type = 1
        const total = 2199
        const list = await Fiction.getAllListByType(`https://m.shuquge.com/sort/1/${type}_`, type,total) //2199
        // ctx.body = Result.success({
        //     results
        // })
        // let values = ''
        // list.forEach(book => {
        //     values += `"${book.text}", ""`
        // })
        const mkdir = `${process.cwd()}/src/public/json/book`
        if (!fs.existsSync(mkdir)){
            fs.mkdirSync(mkdir)
        }
        fs.writeFileSync(`${process.cwd()}/${config.base}/public/json/book/${type}.json`,JSON.stringify(list))
        //batchAddAuthor(list)


        // saveBook(list)
        
        throw new httpErrors.Success({}, '保存成功')
    } catch (error: any) {
        console.log(error)
        if(error instanceof httpErrors.Success){

        }
        else {
            throw new httpErrors.HttpException(error)
        }
    }
    
})


/**
 * 根据type的json往书库批量添加author
 */
async function saveAuthor(){
    const list: List[] = readTypeJson()
    await batchAddAuthor(list)
}

/**
 * 爬取网站所有书的数据（书名、作者），根据书类型（type）分类，保存为json
 */
function uploadJson(){
    cof.forEach(async ({type, total})=>{
        const list = await Fiction.getAllListByType(`https://m.shuquge.com/sort/${type}/0_`,total, type) //2199
        const mkdir = `${process.cwd()}/src/public/json/book`
        if (!fs.existsSync(mkdir)){
            fs.mkdirSync(mkdir)
        }
        fs.writeFileSync(`${process.cwd()}/${config.base}/public/json/book/${type}.json`,JSON.stringify(list))
    })
}

/**
 * 读取book分类json，返回数组
 * @returns 
 */
function readTypeJson(): List[]{
    const list:List[] = []
    cof.forEach(async ({type, total})=>{
        const data:List[]  = JSON.parse(fs.readFileSync(`${process.cwd()}/${config.base}/public/json/book/${type}.json`, 'utf-8'))
        list.push(...data)
    })
    return list
    
}

/**
 * 往数据库批量添加author
 * @param list 
 */
async function batchAddAuthor(list: List[]){
    const nameArr = list.map(item => {
        return item.author
    })
    const authorArr = Array.from(new Set(nameArr)); 
    const values = authorArr.map(item => {
        return `("${item}")`
    })
    const str = `INSERT INTO author (name) VALUES ${values.join(',')}`
    await Mysql.query(str)
}

/**
 * 往数据库批量添加author
 * @param list 
 */
async function batchAddBook(list: List[]){
    const values = list.map(item => {
        return `("${item.text}", ${item.authorId}, "${item.href}", ${item.type})`
    })
    const str = `INSERT INTO book (name, author_id, source_link, type) VALUES ${values.join(',')}`
    await Mysql.query(str)
}

/**
 * 根据从数据库导出的author的json，获取所有author数据
 * @returns 
 */
async function readAuthorJson(): Promise<Author[]>{
    const authorArr: Author[] = JSON.parse(fs.readFileSync(`${process.cwd()}/${config.base}/public/json/book/author.json`, 'utf-8')).RECORDS
    return authorArr
}


/**
 * 将book写入到数据库
 */
async function writeBookJson(){
    // 获取所有作者
    const authorList: Author[] = await readAuthorJson()

    // 获取所有book
    let bookList: List[] = readTypeJson()
    bookList = duplicateRemoval(bookList)
    bookList = bookList.map(item=> {
        let author = authorList.find(a => {
            return a.name === item.author
        })
        if(!author){
            author = {
                name: '未知',
                id: 0
            }
        }
        return {
            ...item,
            authorId: author.id
        }
    })
    await batchAddBook(bookList)
    console.log('保存完毕')
}

/**
 * 去重
 * @param arr 
 * @returns 
 */
function duplicateRemoval(arr: List[]){
    let map = new Map();
    for (let item of arr) {
        if (!map.has(item.text)) {
            map.set(item.text, item);
        }
    }
    return [...map.values()];
}

/**
 * 获取所有书的所有章节，保存为json
 */
async function getAllChapter(){
    // 获取所有book
    // let bookList: List[] = readTypeJson()
    const domain = 'https://m.shuquge.com'
    const href = domain + '/s/151370.html'.replace('s','d')
    
    const bookId = 12231
    const data = await Fiction.getChapterList(href, bookId)
    const mkdir = `${process.cwd()}/src/public/json/book/chapter`
    if (!fs.existsSync(mkdir)){
        fs.mkdirSync(mkdir)
    }
    fs.writeFileSync(`${process.cwd()}/${config.base}/public/json/book/chapter/${bookId}.json`,JSON.stringify(data))
}

export default router